package cn.sjj.util;

import java.text.DecimalFormat;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class TextFormat {

	public static String formatByte(long data, int digit) {
		String pattern = "##.";
		for (int i = 0; i < digit; i++) {
			pattern += "#";
		}
		DecimalFormat format = new DecimalFormat(pattern);
		if (data < 1024) {
			return data + "byte";
		} else if (data < 1024 * 1024) {
			return format.format(data / 1024f) + "KB";
		} else if (data < 1024 * 1024 * 1024) {
			return format.format(data / 1024f / 1024f) + "MB";
		} else if (data < 1024 * 1024 * 1024 * 1024) {
			return format.format(data / 1024f / 1024f / 1024f) + "GB";
		} else {
			return "超出统计返回";
		}
	}

	/**
	 * 把传入的毫秒转化为HH:mm:ss的时间格式
	 * 
	 * @param mills
	 * @return
	 */
	public static String intToTime(int mills) {
		String time = null;
		int h = mills / (60 * 60 * 1000);
		if (h < 10) {
			time = "0" + h;
		} else {
			time = "" + h;
		}
		mills -= h * 60 * 60 * 1000;
		int m = mills / (60 * 1000);
		if (m < 10) {
			time += ":0" + m;
		} else {
			time += ":" + m;
		}
		mills -= m * 60 * 1000;
		int s = mills / 1000;
		if (s < 10) {
			time += ":0" + s;
		} else {
			time += ":" + s;
		}
		return time;
	}

	/*
	 * 匹配IP
	 */
	public static boolean matchIP(String ip) {
		if (null == ip)
			return false;
		String regex = "([1-9]|[1-9]\\d|1\\d{2}|2[0-4]\\d|25[0-5])(\\.(\\d|[1-9]\\d|1\\d{2}|2[0-4]\\d|25[0-5])){3}";
		Pattern pattern = Pattern.compile(regex);
		Matcher matcher = pattern.matcher(ip);
		return matcher.matches();
	}

	/**
	 * 匹配端口
	 * 
	 * @param port
	 * @return
	 */
	public static boolean matchPort(String port) {
		if (null == port)
			return false;
		String regex = "([1-9][0-9]{0,4})";
		Pattern pattern = Pattern.compile(regex);
		Matcher matcher = pattern.matcher(port);
		return matcher.matches();
	}
}
